<template>
	<!-- 申请调换货 -->
	<div class="vmall-cart">
		<view class="header-content">
			<view>需要调换商品</view>
			<view>
				<view v-for="(item, index) in orderProductList" :key="item.orderId"
					class="order-item borderradius my-24 px-32 py-24 bg-white">
					<view class="order-itemscon" @click="goToDetail(item)">
						<image class="cover mr-28" :src="item.productImg" />
						<view class="flex column flex1 py-24">
							<view class="cart-title flex justify-start items-center">
								<view class="tit">{{ item.name }}</view>
							</view>
							<view class="flex justify-between">
								<text class="price1 f-32-B">￥{{ item.unitPrice }}</text>
							</view>
						</view>
						<div class="order-count">
							共{{ item.totalQuantity }}件
						</div>
					</view>
					<div class="borderbottom">
						<view v-for="(items, nindex) in item.skuList" :key="nindex" class="cart-box mb-24">
							<div class="cart-title1 f-24 ellipsis-2">{{ items.skuSpec }}</div>
							<div class="cart-count flex justify-between items-center mt-10">
								{{ items.quantity }}
							</div>
						</view>
					</div>
				</view>
			</view>
		</view>
		<div class="page-content">
			<view class="page-content-head">
				<view class="tit">调换为</view>
				<view class="add-goods" @click="toGoodList">添加商品</view>
			</view>
			<div v-if="cartList.length > 0">
				<Cart ref="cartRef" :cartList="cartList" :selected="false" @delete="onDelete" @select="onSelect" @minus="onMinus"
					@add="onAdd" @select1="onSelect1" />
			</div>
			<!-- 如果无数据，则显示数据 -->
			<div class="empty-container py-40" v-else>
				<Empty :emptyInfo="emptyInfo" />
			</div>
		</div>
		<view class="bottom-button">
			<button class="scan-btn" @click="submitapply" :disabled="loading">
				<up-loading-icon class="loading" color="#fff" size="16" :show="loading"></up-loading-icon>
        		<text>提交申请</text>
			</button>
		</view>
	</div>
</template>
<script setup>
import { IMG_URL2 } from "@/config";
import { shopApi } from "@/api";

import { ref, computed } from "vue"
import Cart from "@/components/cart.vue";
import Empty from "@/components/empty.vue";
import { useExchangeStore } from '@/store/modules/exchange' // Add this import
import { storeToRefs } from 'pinia'
const exchangeStore = useExchangeStore()
let loadStatus = ref('正在加载中')
const cartList = ref([]);
const totalPrice = ref(0);
const CheckAll = ref(false);
const goodsCount = ref(0);
const deleteCount = ref(0);
const showBottom = ref(false);
let orderNo = ref('')
let createTime = ref('')
let goodsexchangeId = ref('')
const loading = ref(false);
let BoundingWidth = ref(30)
const EmptyImage = ref(IMG_URL2 + "empty/cart.png");
const emptyInfo = ref({
	image: EmptyImage,
	width: 300,
	height: 300,
	tip: "暂无数据"
});
// 返回顶部
const backTop = ref(0);
const cartRef = ref();
let orderProductList = ref([])
const { selectedItems,addedItems } = storeToRefs(exchangeStore)
onLoad((options) => {
	let res = wx.getMenuButtonBoundingClientRect();
	console.log(res, 'res');
	BoundingWidth.value = res.width;
	goodsexchangeId.value = options.id;

	// getData();

});

onShow(() => {
	if (selectedItems.value) {
		orderProductList.value = selectedItems.value || [];
	}
	if(addedItems.value){
		cartList.value = addedItems.value.map(item => ({
			selected: true,
			skuList: item.skuList.map(sku => ({
				color: sku.color,
				productSkuId: sku.productSkuId,
				
				quantity:sku.quantity,
				selected: sku.selected,
				size:sku.size,
				skuCode:sku.skuCode,
				skuImg:sku.skuImg,
				skuSpec:sku.skuSpec
			})),
			productId: item.productId,
			productCode: item.productCode,
			name: item.name,
			productImg: item.productImg,
			unitPrice: item.unitPrice,
		}));
	}
});

onUnload(() => {
	
});


const submitapply=()=>{
	if(cartList.value.length==0){
		uni.showToast({
			title: '请选择商品',
			icon: 'none'
		});
		return
	}else{
		let newProductList=[]
		let originalProductList=[]
	// 	"image": "",
    //   "name": "",
    //   "productCode": "",
    //   "productId": 0,
    //   "productSkuCode": "",
    //   "productSkuId": 0,
    //   "quantity": 0,
    //   "spec": ""

	console.log(orderProductList.value,'orderProductList.value')
		orderProductList.value.forEach(item=>{
			item.skuList.forEach(sku=>{
				originalProductList.push({
					image:item.image,
					name:item.name,
					productCode:item.productCode,
					productId:item.productId,
					productSkuCode:sku.productSkuCode,
					productSkuId:sku.productSkuId,
					quantity:sku.quantity,
					spec:sku.skuSpec,
					price:item.price
				})
			})
		})
		console.log(cartList.value,'cartList.value')
		cartList.value.forEach(item=>{
			item.skuList.forEach(sku=>{
				newProductList.push({
					image:item.productImg,
					name:item.name,
					productCode:item.productCode,
					productId:item.productId,
					productSkuCode:sku.skuCode,
					productSkuId:sku.productSkuId,
					quantity:sku.quantity,
					spec:sku.skuSpec,
					price:item.unitPrice
				})
			})
		})
		let data = {
			orderId:goodsexchangeId.value,
			newProductList: newProductList,
			originalProductList: originalProductList
		}
		loading.value = true;
		shopApi.ORDERCONFIRMAPPLYADJUST(data).then((res)=>{
			loading.value = false;
			if(res.code==200){
				uni.showToast({
					title: '申请成功',
					icon: 'none'
				});
				uni.navigateTo({
					url: `/pages/order/index`
				});
			}else{
				uni.showToast({
					title: res.errMsg,
					icon: 'none'
				});
			}
		})
	}
	
}
const toGoodList = () => {
	uni.navigateTo({
		url: `/pages/good/index?type=changegood&orderid=${goodsexchangeId.value}`
	});
}
// 购物车
// 全选
const onSelectAll = (e) => {
	for (let i = 0; i < cartList.value.length; i++) {
		cartList.value[i].selected = !CheckAll.value;
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			cartList.value[i].children[n].selected = !CheckAll.value;
		}
	}
	CheckAll.value = !CheckAll.value;
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 反选
const onSelect = (index) => {
	// cartList.value[index].selected = !cartList.value[index].selected;
	// for (let n = 0; n < cartList.value[index].children.length; n++) {
	// 	cartList.value[index].children[n].selected = !cartList.value[index].children[n].selected
	// }
	// CheckAll.value = !cartList.value.some((item) => item.selected == false);

	

	const item = cartList.value[index];
    item.selected = !item.selected;
    
    item.children.forEach(sku => {
        sku.selected = item.selected;
    });

    CheckAll.value = cartList.value.every(item => 
        item.selected && item.children.every(sku => sku.selected)
    );
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};

// 单个反选
const onSelect1 = (index, nindex) => {
	// cartList.value[index].children[nindex].selected = !cartList.value[index].children[nindex].selected;
	// CheckAll.value = !cartList.value.some((item) => item.selected == false);


	const item = cartList.value[index];
    const sku = item.children[nindex];
    sku.selected = !sku.selected;
    
    item.selected = item.children.every(sku => sku.selected);

    CheckAll.value = cartList.value.every(item => 
        item.selected && item.children.every(sku => sku.selected)
    );
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 加
const onAdd = (index, nindex) => {
	cartList.value[index].children[nindex].quantity++;
	getSumTotal();
};
// 减
const onMinus = (index, nindex) => {
	if (cartList.value[index].children[nindex].quantity == 1) {
		return;
	}
	cartList.value[index].children[nindex].quantity--;
	getSumTotal();
};
// 单个删除选中的商品
const onDelete = (index) => {
	// 处理u-swipe-action-item不复位的问题(要放在删除操作的上方)
	cartRef.value.resetSwipeAction();
	cartList.value.splice(index, 1);
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 批量删除选中的商品
const onDeleteAll = (e) => {
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected == true) {
				cartList.value[i].children.splice(n, 1);
				deleteCount.value = n;
				if(n!=0){
					n = n - 1;
				}
			}
		}
		if (cartList.value[i].children.length == 0) {
			cartList.value.splice(i, 1);
			if(i!=0){
				i = i - 1;
			}
		}
		if (cartList.value[i].selected == true) {
			cartList.value.splice(i, 1);
			if(i!=0){
				i = i - 1;
			}
		}

	}
	totalPrice.value = 0;
	goodsCount.value = 0;
	deleteCount.value = 0;
	CheckAll.value = false;
};
// 删除数量方法
const deleteGoodsCount = () => {
	let count = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		// if (cartList.value[i].selected) {
		// 	count = count + 1;
		// }
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected) {
				// sum += cartList.value[i].children[n].quantity * cartList.value[i].children[n].price;
				count = count + 1;
			}
		}
	}
	deleteCount.value = count;
};
// 合计
const getSumTotal = () => {
	let sum = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected) {
				sum += cartList.value[i].children[n].quantity * cartList.value[i].children[n].price;
			}
		}
		// if (cartList.value[i].selected) {
		// 	sum += cartList.value[i].quantity * cartList.value[i].price;
		// }
	}
	totalPrice.value = sum;
};
// 商品总数量
const getGoodsCount = () => {
	let count = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].children.length; n++) {
			if (cartList.value[i].children[n].selected) {
				// sum += cartList.value[i].children[n].quantity * cartList.value[i].children[n].price;
				count = count + 1;
			}
		}
		// if (cartList.value[i].selected) {
		// 	count = count + 1;
		// }
	}
	goodsCount.value = count;
};
// 编辑
const onRightEdit = () => {
	showBottom.value = !showBottom.value;
};
// 取消删除功能
const onCancel = () => {
	showBottom.value = false;
};
// 结算
const onPayOrder = () => {
	if (goodsCount.value > 0) {
		uni.navigateTo({ url: "/pages/order/confirm" });
	} else {
		uni.showToast({
			title: "您还没有选择商品哦",
			icon: "none",
			mask: true
		});
	}
};

const applyAdjust = () => {
	uni.navigateTo({
		url: `/pagesshop/sales/details?id=${goodsexchangeId.value}`
	});
}
const getData = () => {
	let params = {
		id: goodsexchangeId.value,
	}
	shopApi.ORDERAPPLYADJUST(params).then((res) => {
		if (res.code == 200) {
			createTime.value = res.result.createTime
			orderNo.value = res.result.orderNo
			res.result.productList.forEach(item => {
				item.unitPrice = item.price
				item.productImg = item.image
				if (item.skuList && item.skuList.length > 0) {
					item.skuList.forEach(ele => {
						ele.skuImg = ele.image
						ele.skuSpec = ele.spec
						ele.quantity = ele.availableQuantity
					})
				}
				item.children = item.skuList
			});

			orderProductList.value = res.result.productList
		} else {
			uni.showToast({
				title: res.errMsg,
				icon: "success",
			});
		}

	})

};
</script>

<style>
page {
	background-color: #ededed;
}
</style>
<style lang="scss" scoped>
.shopcartheader {
	width: 100%;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.vmall-cart {
	.header-content {
		background: #fff;
		font-family: PingFang SC;
		font-size: 12px;
		font-weight: 400;
		line-height: 20px;
		text-align: left;
		text-underline-position: from-font;
		text-decoration-skip-ink: none;
		color: rgba(0, 0, 0, 0.6);
		padding: 24rpx;
		box-sizing: border-box;
		margin-bottom: 24rpx;

		.order-item {

			.cover {
				width: 120rpx;
				height: 120rpx;
				border-radius: 8rpx;
			}

			.order-itemscon {
				display: flex;
				align-items: center;
				width: 100%;
				margin-bottom: 12rpx;

				.cart-title {
					font-family: PingFang SC;
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
					text-align: left;
					text-underline-position: from-font;
					text-decoration-skip-ink: none;
					color: rgba(0, 0, 0, 1);
				}

				.price1 {
					color: rgba(0, 0, 0, 1);
					font-family: PingFang SC;
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
					text-align: left;
					text-underline-position: from-font;
					text-decoration-skip-ink: none;

				}

				.order-count {
					color: rgba(0, 0, 0, 0.6);
				}
			}

			.cart-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.borderbottom {
				border-bottom: 1rpx solid #e3e3e3;
			}
		}

		.order-item:last-child {
			.borderbottom {
				border-bottom: none;
			}
		}
	}

	.chevronright-container {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		margin-bottom: 24rpx;
		padding: 24rpx;
		box-sizing: border-box;

		.tit {
			font-family: PingFang SC;
			font-size: 12px;
			font-weight: 400;
			line-height: 20px;
			text-align: left;
			text-underline-position: from-font;
			text-decoration-skip-ink: none;
			color: rgba(0, 0, 0, 0.9);
		}
	}

	.chevronright-content {
		width: 32rpx;
		height: 32rpx;

		.chevronright {
			width: 100%;
			height: 100%;
		}
	}

	.page-content {
		.page-content-head {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #fff;
			padding: 24rpx;
			box-sizing: border-box;

			.tit {
				font-family: PingFang SC;
				font-size: 12px;
				font-weight: 400;
				line-height: 20px;
				text-align: left;
				text-underline-position: from-font;
				text-decoration-skip-ink: none;
				color: rgba(0, 0, 0, 0.9);
			}

			.add-goods {
				width: 100px;
				height: 28px;
				padding: 3px 12px 3px 12px;
				box-sizing: border-box;
				gap: 4px;
				border-radius: 20px;
				opacity: 0px;
				color: #fff;
				background: rgba(214, 142, 68, 1);
				text-align: center;
			}
		}

		.cart-main {
			display: flex;
			margin-right: 20rpx;
		}

		.cart-active {
			float: left;
			width: 100%;
			background: #ffffff;
			border-bottom: 2rpx solid #f2f2f2;
		}

		.cart-image {
			width: 200rpx;
			height: 200rpx;
			float: left;
			margin: 20rpx 10rpx;
		}

		.cart-box {
			display: flex;
			background: white;
			border-radius: 8rpx;
		}

		.cart-boxtwo {
			display: flex;
			flex-direction: column;
		}

		.left_box {
			margin-left: 8rpx;
			margin-top: 20rpx;
			line-height: 60rpx;
		}

		.cart-title {
			font-size: 28rpx;
			line-height: 34rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			overflow: hidden;
			-webkit-line-clamp: 2;
		}

		.cart-count {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.cart-unit {
			font-size: 24rpx;
			color: rgba(214, 142, 68, 1);
		}

		.cart-money {
			display: flex;
			align-items: center;
		}

		.cart-price {
			display: flex;
			color: rgba(214, 142, 68, 1);
			font-size: 30rpx;
			height: 36rpx;
			line-height: 36rpx;
		}

		.cart-specif {
			padding: 4rpx 12rpx;
			box-sizing: border-box;
			background: rgba(214, 142, 68, 1);
			color: #ffffff;
			font-size: 24rpx;
			height: 36rpx;
			line-height: 36rpx;
			margin-bottom: 10rpx;
			border-radius: 50rpx;
		}

		.right {
			float: right;
			width: 5%;
		}

		.right image {
			width: 50rpx;
			height: 50rpx;
			float: right;
			margin-right: 30rpx;
		}

		.input {
			display: block;
			width: 65rpx;
			height: 65rpx;
			line-height: 65rpx;
			text-align: center;
			float: left;
		}

		.cart-add {
			border-left: none;
			border: 2rpx solid #ededed;
			border-radius: 0rpx 40rpx 40rpx 0rpx;
			font-size: 36rpx;
		}

		.cart-reduce {
			border-right: none;
			border: 2rpx solid #ededed;
			border-radius: 40rpx 0rpx 0rpx 40rpx;
			font-size: 36rpx;
		}

		.cart-text {
			width: 90rpx;
			border-top: 2rpx solid #ededed;
			border-bottom: 2rpx solid #ededed;
			font-size: 30rpx;
		}

		.cart-bottom {
			display: flex;
			position: fixed;
			width: 100%;
			height: 88rpx;
			bottom: var(--window-bottom);
			background: #ffffff;
			padding: 0rpx 20rpx;
			box-sizing: border-box;
			border-top: 2rpx solid #f2f2f2;
			z-index: 999;
		}

		.cart-bottom-icon {
			margin-top: 22rpx;

			image {
				width: 40rpx !important;
				height: 40rpx !important;
			}
		}

		.yuan {
			display: block;
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			border: 2rpx solid red;
		}

		.SpCart {
			display: block;
			width: 300rpx;
			height: 300rpx;
		}

		.Sptext {
			font-size: 30rpx;
		}

		.cart-icon {
			margin: 26rpx 20rpx;
			float: left;
		}

		.cart-sum {
			width: 300rpx;
			height: 100%;
			line-height: 87rpx;
			float: left;
			text-align: center;
			margin-left: 20rpx;
			font-size: 28rpx;
		}

		.cart-pay {
			position: absolute;
			width: 230rpx;
			height: 100%;
			background: rgba(214, 142, 68, 1);
			right: 0;
		}

		.cart_pay {
			display: block;
			line-height: 87rpx;
			text-align: center;
			font-size: 30rpx;
			color: white;
		}

		.sum_color {
			color: rgba(214, 142, 68, 1);
			font-size: 25rpx;
		}

		.sum_text {
			font-size: 30rpx;
		}

		.checkAll {
			margin-left: 20rpx;
			line-height: 87rpx;
			font-size: 28rpx;
		}

		.cart-cell {
			display: flex;
			padding: 20rpx 20rpx 0rpx 20rpx;
			box-sizing: border-box;
		}

		.nodata_text {
			background: #ffffff;
			color: black;
			font-size: 28rpx;
			text-align: center;
		}

		.nodata_text {
			image {
				margin-top: 100rpx;
				width: 44%;
				height: 300rpx;
			}
		}

		.icon-main {
			margin: 94rpx 20rpx;
			background: #ffffff;

			image {
				width: 40rpx !important;
				height: 40rpx !important;
			}
		}

		.empty-container {
			background: #ffffff;
		}

		/* 底部 */
		.del-bottom {
			position: fixed;
			width: 100%;
			height: 88rpx;
			bottom: var(--window-bottom);
			background: #ffffff;
			border-top: 2rpx solid #f2f2f2;
			z-index: 999;
		}

		.cart-bottom-edit {
			float: left;
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 28rpx;
			color: rgba(214, 142, 68, 1);
		}

		.cart-bottom-cell {
			float: left;
			width: 49.725%;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 28rpx;
			color: #999999;
			border-right: 2rpx solid #f2f2f2;
		}

		.cart-bottom-cell:last-child {
			border-right: 0rpx;
		}

		.del-color {
			color: rgba(214, 142, 68, 1);
		}
	}

	.wrap {
		padding: 0rpx 10rpx 100rpx 10rpx;
		box-sizing: border-box;
	}

	:deep .u-empty {
		background: #ffffff;
		margin-bottom: 40rpx;
		padding-bottom: 40rpx;
	}
}

.bottom-button {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	box-sizing: border-box;
	background-color: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.scan-btn {
	background-color: rgba(214, 142, 68, 1);
	color: #fff;
	border: none;
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 40rpx;
	font-size: 32rpx;
	display: flex;
    justify-content: center;
}

.cart-right {
	font-size: 26rpx;
}

:deep .u-status-bar {
	display: none !important;
}
</style>